<script>
import axios from "axios";
import { Boot } from '@wangeditor/editor'
import markdownModule from '@wangeditor/plugin-md'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: "Notice",
  components: {Editor, Toolbar,ElImageViewer},
  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server:  this.baseUrl+'/file/upload',
            fieldName: 'file',
            maxFileSize: 5 * 1024 * 1024,
            maxNumberOfFiles: 10,
            headers:{token:localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")).token:null},
            allowedFileTypes: ['image/*'],
            timeout: 20 * 1000,
            onError: (file, err, res) => {
              this.$message.warning('当前选择的图片过大！请选择5M以内')
            },
            customInsert: this.insertImg
          },
          uploadVideo: {
            server:  this.baseUrl+'/file/upload',
            fieldName: 'file',
            maxFileSize: 100 * 1024 * 1024,
            maxNumberOfFiles: 10,
            headers:{token:localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")).token:null},
            allowedFileTypes: ['video/*'],
            timeout: 60 * 1000,
            onError: (file, err, res) => {
              this.$message.warning('当前选择的视频文件过大！请选择100M以内')
            },
            customInsert: this.insertVideo
          },
          codeSelectLang: {
            codeLangs: [
              {text: 'CSS', value: 'css'},
              {text: 'HTML', value: 'html'},
              {text: 'XML', value: 'xml'},
              // 其他
            ]
          }
        },

      },
      mode: 'default',
      tableData: [],
      title: "",
      content: null,
      currentPage: 1,
      pageSize: 5,
      total: 0,
      loading: true,
      multipleSelection: [],
      form: {},
      formLabelWidth: '100px',
      dialogFormVisible1: false,
      dialogFormVisible: false,
      dialogViewVisible: false,
      id: null,
      ids: [],
      coverUrl:this.baseUrl+'/file/upload',
      disabled:false,
      headers:{token:localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")).token:null},
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }
  },
  created() {
    this.load();
    Boot.registerModule(markdownModule);
  },
  methods: {
    load() {
      this.request.get("/notice/page", {
        params: {
          title: this.title,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        }
      }).then(res => {
        this.tableData = res.data.records.filter(notice=>notice.type==2||notice.type==3)
        this.loading = false;
        this.total = this.tableData.length;
        this.coverList = this.tableData.map((notice) => notice.cover);
      });
    },
    onCreated(editor) {
      this.editor = Object.seal(editor);
      // 一定要用 Object.seal() ，否则会报错
    },
    insertImg(res, insertFn) {
      insertFn(res.data)
    },
    insertVideo(res, insertFn) {
      insertFn(res.data)
    },
    view(content) {
      this.content = content;
      this.dialogViewVisible = true;
    },
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) {
        return;
      }
      editor.destroy() // 组件销毁时，及时销毁编辑器
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.load();
    },
    reset() {
      this.title = "";
      this.currentPage = 1;
      this.pageSize = 5;
      this.total = 0;
      this.load();
    },
    handleDelete(id) {
      this.request.delete("/notice/delete/" + id).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((a) => a.id);
      console.log(this.multipleSelection);
    },
    handleBatchRemove() {
      let ids = this.multipleSelection;
      this.request.post("/notice/deleteBatch", ids).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            center: true,
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    handleEdit(row) {
      this.form = row;
      this.content = this.form.content;
      this.dialogFormVisible1 = true;
      this.$nextTick(() => {
        if (this.$refs.img) {
          this.$refs.img.clearFiles();
        }
        if (this.$refs.file) {
          this.$refs.file.clearFiles();
        }
      })
    },
    edit() {
      if (!this.form.title) {
        this.$message({
          type: "warning",
          message: '请输入公告标题',
          center: true
        })
        return;
      }
      this.form.content = this.content;
      this.request.post("/notice/edit/", this.form).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '公告修改成功',
            type: 'success',
            center: true
          });
          this.dialogFormVisible1 = false;
          this.form = {};
          this.load();
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            center: true
          });
        }
      })
    },
    handleSave() {
      this.form = {cover: ''};
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.editor.clear();
        if (this.$refs.img) {
          this.$refs.img.clearFiles();
        }
        if (this.$refs.file) {
          this.$refs.file.clearFiles();
        }
      })
    },
    save() {
      if (!this.form.title) {
        this.$message({
          type: "warning",
          message: '请输入公告标题',
          center: true
        })
        return;
      }
      this.form.content = this.content;
      this.form.type = 2;
      this.request.post("/notice/saveNotice", this.form).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '公告创建成功',
            type: 'success',
            center: true
          });
          this.dialogFormVisible = false;
          this.form = {};
          this.load();
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            center: true
          });
        }
      })
    },
    handleCoverUploadSuccess(res) {
      this.form.cover = res.data;
    },
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    },
    handleRemove(){
      this.form.cover=null;
    },
    headerBg({row, rowIndex}) {
      if (rowIndex == 0) {
        return 'headerBgClass'
      }
    }
  }
}
</script>

<template>
  <div>
    <div>
      <el-input style="width:160px" v-model="title" suffix-icon="el-icon-search" placeholder="请输入名称"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">搜索</el-button>
      <el-button type="warning" style="margin-left: 5px" @click="reset">重置</el-button>
    </div>
    <div style="margin:10px 0px">
      <el-button type="primary" class="ml-5" icon="el-icon-circle-plus-outline" @click="handleSave">新增
      </el-button>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="你确定批量删除吗？"
          @confirm="handleBatchRemove"
          class="ml-5"
      >
        <el-button type="danger" class="ml-5" icon="el-icon-remove-outline" slot="reference"
                   v-if="user.role=='ROLE_ADMIN'">批量删除
        </el-button>
      </el-popconfirm>
    </div>
    <el-table :data="tableData"
              border stripe
              v-loading="loading"
              max-height="550"
              :header-cell-class-name="headerBg"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255,225,255, 0.1)"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55px" align="center"></el-table-column>
      <el-table-column prop="id" label="ID" width="55px" align="center">
      </el-table-column>
      <el-table-column prop="title" width="170px"label="公告标题" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column label="公告内容" width="110px" align="center">
        <template v-slot="scope">
          <el-button type="primary" plain @click="view(scope.row.content)">查看内容</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="公告类型" align="center" width="90px">
        <template slot-scope="scope">
          <el-tag size="medium" :type="scope.row.type===2 ?'success':'warning'">{{scope.row.type===2?'公告':'通知'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publisher" label="状态" align="center" width="90px">
        <template slot-scope="scope" >
          <el-tag size="medium" :type="scope.row.status==='1' ?'primary':'danger'">{{scope.row.status==='1'?'正常':'停用'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publisher" label="发布者" align="center">
      </el-table-column>
      <el-table-column prop="pubdate" label="发布时间" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="success" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="handleDelete(scope.row.id)"
          >
            <el-button type="danger" icon="el-icon-delete" slot="reference" v-if="user.role=='ROLE_ADMIN'">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding:10px 0px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="新增公告" :visible.sync="dialogFormVisible" width="60%" style="min-height: 600px"
               :close-on-click-modal="false">
      <el-form :model="form" label-width="80px" size="small" style="width: 90%">
        <el-form-item label="公告标题">
          <el-input v-model="form.title" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="avatar-uploader"
              action= "avatarUrl"
              :headers="headers"
              style="display: inline"
              :show-file-list="false"
              :on-success="handleCoverUploadSuccess"
              :before-upload="beforeCoverUpload">
            <img v-if="form.cover" :src="form.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button v-if="form.cover" type="text" @click="handleRemove" style="font-size: 30px;color: #8c939d;position: absolute;left: 35px;top:30px"><i class="el-icon-delete"></i></el-button>
        </el-form-item>
        <el-form-item label="公告类型">
        <el-select v-model="form.type" placeholder="请选择">
          <el-option  value=2 label="公告"></el-option>
          <el-option  value=3 label="通知"></el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="form.status"  label="1">正常</el-radio>
          <el-radio v-model="form.status"  label="0">停用</el-radio>
        </el-form-item>
        <el-form-item label="公告内容">
          <template>
            <div style="border: 1px solid #ccc;">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="content"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
              />
            </div>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑公告" :visible.sync="dialogFormVisible1" width="60%" style="min-height: 600px"
               :close-on-click-modal="false">
      <el-form :model="form" label-width="80px" size="small" style="width: 90%">
        <el-form-item label="公告标题">
          <el-input v-model="form.title" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="avatar-uploader"
              :action="coverUrl"
              :headers="headers"
              style="display: inline"
              :show-file-list="false"
              :on-success="handleCoverUploadSuccess"
              :before-upload="beforeCoverUpload">
            <img v-if="form.cover" :src="form.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button v-if="form.cover" type="text" @click="handleRemove" style="font-size: 30px;color: #8c939d;position: absolute;left: 35px;top:30px"><i class="el-icon-delete"></i></el-button>
        </el-form-item>
        <el-form-item label="公告类型">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option  :value=2 label="公告"></el-option>
            <el-option  :value=3 label="通知"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="form.status"  label="1">正常</el-radio>
          <el-radio v-model="form.status"  label="0">停用</el-radio>
        </el-form-item>
        <el-form-item label="公告内容">
          <template>
            <div style="border: 1px solid #ccc;">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="content"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
              />
            </div>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="内容" :visible.sync="dialogViewVisible" width="60%">
      <el-card>
        <div v-html="content"></div>
      </el-card>
    </el-dialog>
  </div>

</template>

<style src="@wangeditor/editor/dist/css/style.css">
/*
.sketch_content {
  overflow: auto;
  height: 400px;
  border-top: 1px solid rgb(151, 163, 174);
  border-bottom: 1px solid rgb(151, 163, 174);
  padding: 0px 30px 11px 27px;
}
.sketch_content::-webkit-scrollbar {
  width: 3px;
}
.sketch_content::-webkit-scrollbar-thumb {
  background: #8798AF;
  border-radius: 2px;
}
.sketch_content::-webkit-scrollbar-track {
  background: transparent;
}
*/
.headerBgClass {
  background-color: #cccccc !important;
}

</style>

